package model;

import java.awt.geom.Point2D;
import java.util.ArrayList;
import javax.swing.JOptionPane;

public class RegulaFalsi {
    public static ArrayList<Iteration> approximate(Polynomial poly, Point2D.Double point1, Point2D.Double point2, int maxIterations, double error) {
    	ArrayList<Iteration> iterationSet = new ArrayList<Iteration>();
        
        if (point1.y * point2.y >= 0){
    		JOptionPane.showMessageDialog(null, "f(xi) and f(xi+1) should be of different signs", "Error", JOptionPane.ERROR_MESSAGE);
        	return iterationSet;
        }
        
        double newPointX;
        boolean stopFlag = false;
        
        do {
            newPointX = point2.x - (point2.y*(point2.x-point1.x))/(point2.y-point1.y);
            Point2D.Double newPoint = new Point2D.Double(newPointX, poly.evaluate(newPointX));

            iterationSet.add(new Iteration(point1, point2, newPoint));
            
            if(Math.min(Math.abs(point1.x-newPointX),Math.abs(point2.x-newPointX)) <= error)
            	stopFlag = true;

            if (point1.y * newPoint.y > 0)
                point1 = newPoint;
            else
                point2 = newPoint;
            
        } while (iterationSet.size() < maxIterations && !stopFlag && point1.y*point2.y < 0);
     
        return iterationSet;
    }
}